<template>
  <view class="login-page">
    <uni-nav-bar title="智能数采系统" fixed statusBar class="navbar"></uni-nav-bar>
    <!-- tabs标签页 -->
    <view class="tabs">
      <view
        class="tabs-item"
        v-for="(item, index) in tabs"
        :key="item.title"
        :class="{ active: activeIndex === index }"
        @click="activeIndex = index"
      >
        <view class="tabs-item-title">{{ item.title }}</view>
      </view>
    </view>
    <!-- 登录 -->
    <view class="login-form" v-if="activeIndex === 0">
      <view class="logo-img">
        <image class="img" src="/src/static/images/logo.jpg" mode="aspectFit" />
      </view>
      <uni-forms ref="loginForm" :model="loginData" :rules="loginRules" label-position="top">
        <uni-forms-item label="Email" name="login" required>
          <uni-easyinput v-model="loginData.login" placeholder="Email" />
        </uni-forms-item>
        <uni-forms-item label="密码" name="password" required>
          <uni-easyinput v-model="loginData.password" placeholder="密码" type="password" />
        </uni-forms-item>
      </uni-forms>
      <view class="login-button" @click="onSubmit">登录</view>
      <!-- <view class="background-img">
        <image class="img" src="/src/static/images/login_bg.jpg" mode="aspectFill" />
      </view> -->
    </view>
    <!-- 离线操作 -->
    <view class="offline" v-if="activeIndex === 1" @click="chooseExcelFile">
      <!-- #ifndef APP-PLUS -->
      <view class="upload">选择工单 上传 </view>
      <view> <uni-icons type="right" color="$brand-theme-color" size="24" /></view>
      <!-- #endif -->

      <!-- #ifdef APP-PLUS -->
      <view class="container">
        <web-view src="/hybrid/html/local.html" @message="handleMessage"></web-view>
      </view>
      <!-- #endif -->
    </view>
    <!-- <navigator url="/pagesTest/test1/test1" open-type="navigate" hover-class="navigator-hover">
      测试
    </navigator> -->
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { apiGetToken } from '@/api/apis'
import { useUserStore, useOfflineStore } from '@/stores/'
import * as XLSX from 'xlsx'
// import { pathToBase64 } from 'image-tools'
// import { openFile, readAndroidAbsolutePath } from '@/utils/file.js'
const userStore = useUserStore()
const offlineStore = useOfflineStore()
const jsonData = ref({})
// tabs标签
const tabs = ref([
  {
    title: '电脑版',
  },
  {
    title: '手机版',
  },
])
const activeIndex = ref(0)
// 登录表单
const loginForm = ref(null)
// 登录表单数据
const loginData = ref({
  login: 'lg',
  password: '11',
})
// 登录表单验证规则
const loginRules = ref({
  login: {
    rules: [
      {
        required: true,
        errorMessage: 'Email不能为空',
      },
    ],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '密码不能为空',
      },
    ],
  },
})
// 登录
async function onLogin() {
  const app = getApp()
  //试着有网情况登录，有网则验证登录，无网则使用store数据
  try {
    const res = await apiGetToken(loginData.value)
    // console.log(res)
    // #ifndef H5
    userStore.setToken(res.cookies[0])
    // #endif
    // console.log(Object.values(res.data.result.user_companies.allowed_companies).map((v=>v.id)))
    const userInfo = {
      company_id: res.data.result.company_id,
      env_company: res.data.result.env_company,
      uid: res.data.result.uid,
      username: res.data.result.username,
      name: res.data.result.name,
      //数据中的组织(company_id)必须在下面登录用户所属组织的列表内才能查看，即组织隔离
      companies: Object.values(res.data.result.user_companies.allowed_companies).map((v) => v.id),
    }
    // console.log(userInfo)
    userStore.setUserInfo(userInfo)
    // 有网络时设置全局标志
    app.globalData.hasNetwork = true
  } catch (err) {
    console.log(err)
    // 无网络情况，设置全局标志为false,这时利用存储数据store数据渲染，无需验证登录用户。
    app.globalData.hasNetwork = false
  }
  app.globalData.isFromLogin = true // 设置标志,是从登录页面跳转的
  uni.switchTab({
    url: '/pages/index/index',
  })
  // }

  uni.showToast({
    icon: 'success',
    title: '登录成功',
  })
}
// 校验
function onSubmit() {
  loginForm.value
    .validate()
    .then(async (res) => {
      onLogin()
    })
    .catch((err) => {
      console.log('err', err)
    })
}
//使用webview,下面不用了
async function chooseExcelFile() {
  let workbook = {}
  // if (uni.getSystemInfoSync().platform === 'android') {
  //#ifdef APP-PLUS
  uni.navigateTo({ url: '/pages/file/file' })
  // })
  //#endif
  // } else {
  //#ifdef H5
  try {
    // 1. 选择文件
    const files = await uni.chooseFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
    })
    console.log(files.tempFiles[0])
    const file = files.tempFiles[0]

    // 2. 读取文件内容
    const arrayBuffer = await readFileAsArrayBuffer(file)
    console.log(arrayBuffer)

    // 3. 解析 XLSX 文件
    workbook = XLSX.read(arrayBuffer, { type: 'array' })
    // 4. 获取第一个工作表
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]

    // 5. 转换为 JSON
    const jsonData = XLSX.utils.sheet_to_json(worksheet)
    console.log('转换后的 JSON 数据:', jsonData)
    offlineStore.setRecords(jsonData)
    uni.navigateTo({ url: '/pages/offline/offline' })

    // return jsonData
  } catch (error) {
    console.error('转换失败:', error)
    uni.showToast({
      title: '文件转换失败',
      icon: 'none',
    })
    throw error
  }
  // #endif

  // #ifdef MP-WEIXIN
  console.log('weixin')
  uni.chooseMessageFile({
    count: 1,
    type: 'file',
    success: (res) => {
      const tempFile = res.tempFiles[0]
      // console.log(tempFile.path)
      readExcel(tempFile.path)
    },
    fail: (err) => {
      console.error('选择文件失败:', err)
      uni.showToast({
        title: '选择文件失败',
        icon: 'none',
      })
    },
  })
  //#endif

  //#ifdef APP-PLUS
  //待完善
  //#endif
}
//使用webview,下面不用了
//微信小程序获取excel的jsondata
function readExcel(filePath) {
  // 读取文件
  const fs = uni.getFileSystemManager()
  fs.readFile({
    filePath: filePath,
    encoding: 'binary', // 重要：必须使用binary编码
    success: (res) => {
      try {
        // 解析Excel
        const workbook = XLSX.read(res.data, { type: 'binary' })

        // 获取第一个工作表
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]

        // 转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        console.log('转换后的 JSON 数据:', jsonData)
        offlineStore.setRecords(jsonData)
        uni.navigateTo({ url: '/pages/offline/offline' })

        // uni.showToast({
        //   title: '转换成功',
        //   icon: 'success',
        // })
      } catch (e) {
        console.error('解析Excel失败:', e)
        uni.showToast({
          title: '解析Excel失败',
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      console.error('读取文件失败:', err)
      uni.showToast({
        title: '读取文件失败',
        icon: 'none',
      })
    },
  })
}
//使用webview,下面不用了
//H5获取excel的jsondata
function readFileAsArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()

    fileReader.onload = (e) => {
      // console.log('e.target.result', e.target.result)
      resolve(e.target.result)
    }

    fileReader.onerror = (error) => {
      reject(error)
    }

    fileReader.readAsArrayBuffer(file)
  })
}
//下面是webview 返回的结果处理转发至ofline
const handleMessage = (e) => {
  console.log(e.detail.data)
  offlineStore.records = e.detail.data[0].action
  uni.navigateTo({ url: '/pages/offline/offline' })
}
</script>

<style lang="scss" scoped>
/* 全局优化 */
.login-page {
  background: linear-gradient(135deg, #f0f4fd 0%, #e3eeff 100%);
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 导航栏优化 */
.navbar {
  background: linear-gradient(90deg, #1a73e8 0%, #0d47a1 100%) !important;
  color: white !important;
  box-shadow: 0 2px 10px rgba(13, 71, 161, 0.3);

  :deep(.uni-nav-bar-text) {
    // color: white !important;
    color: #11468a !important;
    font-weight: 600;
  }
}

/* 标签页样式优化 */
.tabs {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  position: relative;

  &-item {
    padding: 0 25px;
    position: relative;
    z-index: 1;
    transition: all 0.3s ease;

    &-title {
      padding: 10px 5px;
      font-size: 18px;
      font-weight: 500;
      color: #718096;
      position: relative;
      transition: all 0.3s;
    }

    &.active {
      .tabs-item-title {
        color: #1a73e8;
        font-weight: 600;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40px;
        height: 3px;
        background: #1a73e8;
        border-radius: 10px;
      }
    }
  }
}

/* 登录表单优化 */
.login-form {
  max-width: 500px;
  margin: 30px auto 0;
  padding: 30px;
  background: white;
  border-radius: 24px;
  box-shadow: 0 10px 30px rgba(26, 115, 232, 0.1);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.6s ease forwards;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(90deg, #1a73e8 0%, #0d47a1 100%);
  }

  .logo-img {
    display: flex;
    justify-content: center;
    margin: 15px 0 25px;

    .img {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      box-shadow: 0 8px 20px rgba(26, 115, 232, 0.15);
      border: 3px solid white;
    }
  }

  /* 表单元素优化 */
  :deep(.uni-forms-item) {
    margin-bottom: 25px;

    .uni-forms-item__label {
      font-weight: 600;
      color: #2d3748;
      padding-bottom: 8px;
      font-size: 16px;
    }

    .uni-easyinput {
      border-radius: 12px;
      border: 1px solid #e2e8f0;
      transition: all 0.3s;
      overflow: hidden;

      &:focus-within {
        border-color: #1a73e8;
        box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.2);
      }

      .uni-easyinput__content-input {
        padding: 14px 16px;
        font-size: 16px;
      }
    }
  }

  .login-button {
    background: linear-gradient(90deg, #1a73e8 0%, #0d47a1 100%);
    color: white;
    border-radius: 14px;
    height: 54px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 600;
    margin-top: 10px;
    box-shadow: 0 6px 15px rgba(26, 115, 232, 0.3);
    transition: all 0.3s;
    position: relative;
    overflow: hidden;

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 200%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
      transition: all 0.6s;
    }

    &:active {
      transform: translateY(3px);
      box-shadow: 0 3px 8px rgba(26, 115, 232, 0.3);

      &::after {
        left: 100%;
      }
    }
  }
}

/* 离线操作区域优化 */
.offline {
  max-width: 500px;
  margin: 30px auto 0;
  padding: 30px;
  background: white;
  border-radius: 24px;
  box-shadow: 0 10px 30px rgba(26, 115, 232, 0.1);
  animation: fadeInUp 0.6s ease 0.2s forwards;
  opacity: 0;

  .upload {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 54px;
    background: linear-gradient(90deg, #38b2ac 0%, #319795 100%);
    color: white;
    border-radius: 14px;
    font-size: 18px;
    font-weight: 600;
    box-shadow: 0 6px 15px rgba(56, 178, 172, 0.3);
    transition: all 0.3s;

    &:active {
      transform: translateY(3px);
      box-shadow: 0 3px 8px rgba(56, 178, 172, 0.3);
    }
  }

  > view:last-child {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .uni-icons {
      font-size: 28px;
      color: #1a73e8;
    }
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-form,
  .offline {
    padding: 20px;
    margin: 20px 15px 0;
  }

  .tabs-item {
    padding: 0 15px;
  }
}
</style>
<!-- <style lang="scss" scoped>
.img {
  display: line-block;
  width: 60%;
  height: 60%;
}
.login-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - var(--window-top));
  height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom));
  height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));
  // height: 100vh;
  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    // padding: 16px 40px;
    border-bottom: 1px solid $border-color;
    &-item {
      height: 50px;
      // width: 40px;
      line-height: 50px;
    }
    .active {
      color: $brand-theme-color;
      font-weight: 700;
      border-bottom: 2px solid $brand-theme-color;
    }
  }
  .login-form {
    position: relative;
    flex: 1;
    padding: 10px 18px;
    height: 100%;
    // background: url('@/static/images/login_bg.jpg') no-repeat top center/cover;
    .logo-img {
      width: 100%;
      height: 100px;
    }
    :deep(.uni-forms-item__label) {
      width: fit-content !important;
      font-size: 16px;
      font-weight: 700;
      color: $text-font-color-1;
    }
    :deep(.is-input-border) {
      background: transparent !important;
    }
    :deep(.is-focused) {
      border-color: $bg-white-color !important;
      .uni-icons {
        color: $bg-white-color !important;
      }
    }
    .login-button {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 46px;
      margin: 24px 0;
      background: $brand-theme-color;
      color: #fff;
      border-radius: 10px;
    }
    .background-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
    }
    .logo-img {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
      margin-top: 10px;
    }
  }
  .offline {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 30px 30px 0;
    color: $uni-text-color-grey;
  }
}
</style> -->
